package com.magicmovie.service.impl;

import com.magicmovie.entity.User;
import com.magicmovie.mapper.UserMapper;
import com.magicmovie.service.UserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByUserName(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    @Transactional(readOnly = false)
    public void insert(@RequestBody User user) {
        String password = user.getPassword();
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setSalt(salt);
        user.setPassword(encryptPassword("SHA-256", password,salt,1));
        userMapper.insert(user);
    }

    @Override
    @Transactional(readOnly = false)
    public void update(@RequestBody User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public List<Map<String, Object>> findByParams(@RequestBody Map<String, Object> params) {
        return userMapper.findByParams(params);
    }

    @Override
    public User findByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional(readOnly = false)
    public void delete(Integer id) {
        userMapper.deleteByPrimaryKey(id);
    }

    /**
     * 获取加密后的密码，需要指定 hash迭代的次数
     *
     * @param hashAlgorithm  hash算法名称 MD2、MD5、SHA-1、SHA-256、SHA-384、SHA-512、etc。
     * @param password       需要加密的密码
     * @param salt           盐
     * @param hashIterations hash迭代的次数
     * @return 加密后的密码
     */
    public static String encryptPassword(String hashAlgorithm, String password, String salt, int hashIterations) {
        SimpleHash hash = new SimpleHash(hashAlgorithm, password, salt, hashIterations);
        return hash.toString();
    }
}
